#! usr/lib/python
# coding:utf-8
"""
@author: jeffxun
@date  : 2012-06-22
"""

import re
import os
import codecs

class ReadIni(object):
    """Read config files"""
    def __init__(self,filename=None):
        """"""
        if filename:
            self.OpenFile(filename)

    def OpenFile(self,filename):
        self._filename = filename
        if self._filename.find(".ini") ==-1:
			self._filename +=".ini"
        if not os.path.isfile(self._filename):
            raise NameError,"%s is not exist!"%self._filename
        else :
            try :
                self.__pf = codecs.open(self._filename,'r',"utf-8")
            except  Exception,e:
                print e

        (self.__options,self.__sections,self.__values) = self.__readfile__()
    def __readfile__(self):
        p = r"^\[.*?\]$"
        s = '^.*?='
        options = []
        setctions = {}
        text = {}

        for line in self.__pf:
            if line.startswith(";") :
                continue
            #print line.strip()
            m =  re.findall(p,line.strip())
            if  m :
                options.append(m[0][1:-1])
                continue
            else:
                n = re.findall(s,line)

                if n:
                    try:
                        setctions[options[-1]]=n[0][:-1].strip()
                        line =line[len(n[0]):].strip('\n')
                        line = line.strip()
                        text[(options[-1],setctions[options[-1]])] = line
                    except Exception,e:
                        #print e
                        pass
                else:
                    try:
                        line =line.strip('\n')
                        line = line.strip()
                        #print line
                        text[(options[-1],setctions[options[-1]])] += line
                    except Exception,e:
                        #print e
                        pass
        return options,setctions,text

    def __getoptions__(self):
        return self.__options

    def __getsections__(self,option):
        """"""
        return self.__sections

    def ReadConfig(self,option,section):
        if self.__values.has_key((option,section)):
            return self.__values[(option,section)]
        else:
            raise KeyError,"(%s,%s) key is not exist!"%(option,section)
            
    def ReadValue(self,option,section):
        if self.__values.has_key((option,section)):
            return self.__values[(option,section)]
        else:
            raise KeyError,"(%s,%s) key is not exist!"%(option,section)
            
    def ReadIntValue(self,option,section):
        if self.__values.has_key((option,section)):
            return int(self.__values[(option,section)])
        else:
            raise KeyError,"(%s,%s) key is not exist!"%(option,section)
    def ToList(self,buf):
        result = []
        #value = value[1:len(buf)-1]
        p =r"\(.*?\)"
        m = re.findall(p,buf)
        if not m :
        	return None
        else :
        	for i in m:
        		i=i[1:len(i)-1]
        		i = tuple(i.split(","))
        		result.append(i)
		return result

    def ToDict(self,buf):
		result = {}
		p = r"\d:\[.*?\]"
		m = re.findall(p,buf)
		if not m:
			return None
		else :
			for i in m:
				key = int(i[:i.find(":")])
				value = i[i.find(":")+1:]
				value =value[1:len(value)-1]
				result[key] = value
		return result
if __name__ == "__main__":
    conf = ReadIni()
    conf.OpenFile("../../config/warConfig")
    print conf.ReadConfig('A_Player','GenName')